"""
订单系统数据模型模块
定义数据库表结构和相关枚举类型
"""
from sqlmodel import SQLModel, Field, Relationship, Column, JSON, DateTime
from typing import Optional, List, Dict, Any
from datetime import datetime
from enum import Enum
import uuid


class OrderStatus(str, Enum):
    """订单状态枚举类"""
    PENDING = "pending"          # 待处理
    PAID = "paid"                # 已支付
    PROCESSING = "processing"    # 处理中
    MANUFACTURING = "manufacturing"  # 制造中
    SHIPPED = "shipped"          # 已发货
    DELIVERED = "delivered"      # 已送达
    CANCELLED = "cancelled"      # 已取消
    REFUNDED = "refunded"        # 已退款


class PaymentStatus(str, Enum):
    """支付状态枚举类"""
    PENDING = "pending"          # 待支付
    SUCCESS = "success"          # 支付成功
    FAILED = "failed"            # 支付失败
    REFUNDED = "refunded"        # 已退款


class PaymentMethod(str, Enum):
    """支付方式枚举类"""
    ALIPAY = "alipay"            # 支付宝
    WECHAT = "wechat"            # 微信支付
    SHOPIFY = "shopify"          # Shopify支付


class Order(SQLModel, table=True):
    """订单表模型"""
    id: Optional[int] = Field(default=None, primary_key=True)
    """订单ID，主键"""
    order_number: str = Field(unique=True, index=True)
    """订单编号，唯一索引"""
    user_id: int = Field(default=1)
    """用户ID"""
    
    total_amount: float = Field(default=0.0)
    """订单总金额"""
    currency: str = Field(default="CNY")
    """货币类型"""
    
    model_id: Optional[int] = Field(default=None)
    """模型ID（关联3D模型）"""
    model_parameters: Dict[str, Any] = Field(default={}, sa_column=Column(JSON))
    """模型参数，JSON格式存储"""
    
    status: OrderStatus = Field(default=OrderStatus.PENDING)
    """订单状态"""
    payment_status: PaymentStatus = Field(default=PaymentStatus.PENDING)
    """支付状态"""
    payment_method: Optional[PaymentMethod] = None
    """支付方式"""
    
    shopify_order_id: Optional[str] = Field(default=None, unique=True)
    """Shopify订单ID"""
    shopify_order_data: Dict[str, Any] = Field(default={}, sa_column=Column(JSON))
    """Shopify订单数据，JSON格式存储"""
    
    created_at: datetime = Field(default_factory=datetime.utcnow)
    """创建时间"""
    updated_at: datetime = Field(default_factory=datetime.utcnow)
    """更新时间"""


class OrderItem(SQLModel, table=True):
    """订单项表模型"""
    id: Optional[int] = Field(default=None, primary_key=True)
    """订单项ID，主键"""
    order_id: int = Field(foreign_key="order.id")
    """订单ID，外键关联order表"""
    product_id: int = Field(default=1)
    """产品ID"""
    
    quantity: int = Field(default=1)
    """数量"""
    unit_price: float = Field(default=0.0)
    """单价"""
    total_price: float = Field(default=0.0)
    """总价"""
    
    material: str = Field(default="PLA")
    """材料类型"""
    color: str = Field(default="white")
    """颜色"""
    size: str = Field(default="medium")
    """尺寸"""


class Payment(SQLModel, table=True):
    """支付表模型"""
    id: Optional[int] = Field(default=None, primary_key=True)
    """支付ID，主键"""
    order_id: int = Field(foreign_key="order.id")
    """订单ID，外键关联order表"""
    
    payment_number: str = Field(unique=True, index=True)
    """支付编号，唯一索引"""
    amount: float = Field(default=0.0)
    """支付金额"""
    currency: str = Field(default="CNY")
    """货币类型"""
    
    payment_method: PaymentMethod
    """支付方式"""
    payment_data: Dict[str, Any] = Field(default={}, sa_column=Column(JSON))
    """支付相关数据，JSON格式存储"""
    
    status: PaymentStatus = Field(default=PaymentStatus.PENDING)
    """支付状态"""
    paid_at: Optional[datetime] = None
    """支付时间"""
    
    created_at: datetime = Field(default_factory=datetime.utcnow)
    """创建时间"""


class Manufacturer(SQLModel, table=True):
    """生产厂商表模型"""
    id: Optional[int] = Field(default=None, primary_key=True)
    """厂商ID，主键"""
    name: str = Field(index=True)
    """厂商名称，索引"""
    code: str = Field(unique=True, index=True)
    """厂商编码，唯一索引"""
    
    contact_person: str = Field(default="")
    """联系人"""
    email: str = Field(default="")
    """邮箱"""
    phone: str = Field(default="")
    """电话"""
    address: str = Field(default="")
    """地址"""
    
    api_endpoint: Optional[str] = None
    """API端点"""
    api_key: Optional[str] = None
    """API密钥"""
    api_secret: Optional[str] = None
    """API密钥密码"""
    
    supported_materials: List[str] = Field(default=[], sa_column=Column(JSON))
    """支持的材料列表，JSON格式存储"""
    capabilities: List[str] = Field(default=[], sa_column=Column(JSON))
    """生产能力列表，JSON格式存储"""
    
    is_active: bool = Field(default=True)
    """是否激活"""
    created_at: datetime = Field(default_factory=datetime.utcnow)
    """创建时间"""


class ProductionJob(SQLModel, table=True):
    """生产任务表模型"""
    id: Optional[int] = Field(default=None, primary_key=True)
    """任务ID，主键"""
    order_id: int = Field(foreign_key="order.id")
    """订单ID，外键关联order表"""
    manufacturer_id: int = Field(foreign_key="manufacturer.id")
    """厂商ID，外键关联manufacturer表"""
    
    job_number: str = Field(unique=True, index=True)
    """任务编号，唯一索引"""
    
    model_file_url: str = Field(default="")
    """模型文件URL"""
    production_parameters: Dict[str, Any] = Field(default={}, sa_column=Column(JSON))
    """生产参数，JSON格式存储"""
    
    status: str = Field(default="pending")
    """任务状态"""
    manufacturer_status: Optional[str] = None
    """厂商返回的状态"""
    
    sent_at: Optional[datetime] = None
    """发送时间"""
    confirmed_at: Optional[datetime] = None
    """确认时间"""
    production_started_at: Optional[datetime] = None
    """生产开始时间"""
    production_completed_at: Optional[datetime] = None
    """生产完成时间"""
    
    tracking_number: Optional[str] = None
    """物流单号"""
    shipment_data: Dict[str, Any] = Field(default={}, sa_column=Column(JSON))
    """物流数据，JSON格式存储"""
    
    created_at: datetime = Field(default_factory=datetime.utcnow)
    """创建时间"""
    updated_at: datetime = Field(default_factory=datetime.utcnow)
    """更新时间"""


class ShopifyStore(SQLModel, table=True):
    """Shopify店铺表模型"""
    id: Optional[int] = Field(default=None, primary_key=True)
    """店铺ID，主键"""
    store_name: str = Field(unique=True, index=True)
    """店铺名称，唯一索引"""
    shopify_domain: str = Field(unique=True, index=True)
    """Shopify域名，唯一索引"""
    
    api_key: str = Field(default="")
    """API密钥"""
    api_secret: str = Field(default="")
    """API密钥密码"""
    access_token: Optional[str] = None
    """访问令牌"""
    
    webhook_id: Optional[str] = None
    """Webhook ID"""
    
    is_active: bool = Field(default=True)
    """是否激活"""
    created_at: datetime = Field(default_factory=datetime.utcnow)
    """创建时间"""